package com.xunmall.web.controller;

import com.xunmall.base.dto.Result;
import com.xunmall.web.model.PageResult;
import com.xunmall.web.model.dto.RoleDTO;
import com.xunmall.web.model.vo.RoleVO;
import com.xunmall.web.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * Created by wangyanjing on 2018/11/6.
 */
@Controller
@RequestMapping("/system/role")
public class SystemRoleWebController extends BaseWebController {

    @Autowired
    private RoleService roleService;

    private String viewPath = "system/role/";

    @RequestMapping("/list")
    public ModelAndView listPage(RoleVO roleVO) {
        ModelAndView mv = new ModelAndView();
        PageResult pageResult = roleService.findRoleListByCondition(roleVO);
        mv.setViewName(viewPath + "list");
        mv.addObject("pageResult", pageResult);
        return mv;
    }

    @RequestMapping(value = "/add_page")
    public String addPage() {
        return viewPath + "add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Object add(@Valid RoleDTO roleDTO) {
        Result result = roleService.saveRole(roleDTO);
        if (result.getSuccess()) {
            return jsonReturn(200);
        } else {
            return jsonReturn(300, result.getMessage());
        }
    }

    @RequestMapping(value = "/edit")
    public String edit(@RequestParam("id") String id, HttpServletRequest request) {
        Result result = roleService.findRoleById(id);
        request.setAttribute("role", result.getData());
        return viewPath + "edit";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(RoleVO roleVO) {
        Result result = roleService.updateRole(roleVO);
        if (result.getSuccess()) {
            return jsonReturn(200);
        } else {
            return jsonReturn(300, result.getMessage());
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(@RequestParam("id") String id) {
        Result result = roleService.deleteUserById(id);
        if (result.getSuccess()) {
            return jsonReturn(200, false);
        } else {
            return jsonReturn(300, result.getMessage(), false);
        }
    }

}
